#!/usr/local/bin/python
# Author: Jimmy Saw
# Date: 01/10/2010
# This script parses 
# Needs 2 files: 
# First file looks like this:
# 192360421 50S ribosomal protein L3 [Cellvibrio japonicus Ueda107]
# 217975201 50S ribosomal protein L3 [Shewanella baltica OS223]
# 217967369 ribosomal protein L3 [Dictyoglomus turgidum DSM 6724]
# 118579119 50S ribosomal protein L3 [Pelobacter propionicus DSM 2379]
#
# Second file looks like this:
# 7 S.grandis.chr_1_7   ZP_01693144.1 124008450
# 8 S.grandis.chr_1_8   - Empty
# 9 S.grandis.chr_1_9   - Empty
# 10  S.grandis.chr_1_10  ZP_01897028.1 149908365

import sys, re

filename = sys.argv[1]

gilist = sys.argv[2]

f = open(filename, "r")

g = open(gilist, "r")

lines = f.readlines()

lines2 = g.readlines()

mydict = {}

for line in lines:
    linetoparse = line
    l = linetoparse.split('\t')
    mydict[l[0]] = l[1].rstrip()

num = len(lines2)

i = 0

#To match stuffs like this:
#UDP-3-O-[3-hydroxymyristoyl] glucosamine N-acyltransferase [Acetobacter pasteurianus IFO 3283-01]
m1 = re.compile('(.*\[.*\].*)\[(.*)\]')

#To match stuffs like this:
#50S ribosomal protein L3 [Shewanella piezotolerans WP3]
m2 = re.compile('(.*)\[(.*)\]')

while i < num:
    gistoparse = lines2[i]
    gis = gistoparse.split('\t')
    iden = gis[1]
    gi = gis[3].rstrip()
    if gi != 'Empty':
        if mydict.has_key(gi):
            d = mydict[gi]
            if m1.match(d):
                pattern = m1.match(d)
                print iden, "\t", pattern.group(1), "\t", pattern.group(2)
            else:
                pattern = m2.match(d)
                print iden, "\t", pattern.group(1), "\t", pattern.group(2)
        else:
            print iden, "\t", "Not in cluster"
    else:
        print iden, "\t", "hypothetical protein"
    i += 1

f.close()
g.close()
